//
//  YWModifyMeterReadingTableViewController.m
//  maintain
//
//  Created by 烟雨云渊 on 2017/5/12.
//  Copyright © 2017年 ewin. All rights reserved.
//

#import "YWModifyMeterReadingTableViewController.h"
#import "UIColor+CustomColors.h"
#import "YWMacro.h"

//#import "YWImageView.h"
#import "YWPhotoView.h"
#import "YWCommonTool.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "MBProgressHUD.h"

#import "YWMeterReadingDetailRecordCell.h"
#import "YWLocationCell.h"
#import "YWWriteMeterReadingNumberCell.h"
#import "YWWriteNoteCell.h"

#import "YWMeterReadingManager.h"
#import "YWEquipmentManager.h"
#import "YWBuildingManager.h"

@interface YWModifyMeterReadingTableViewController ()<YWWriteMeterReadingNumberCellDelegate,YWWriteNoteCellDelegate>{
    NSString * noteString;
    NSString *writtingReadingNumber;
}
@property (nonatomic,strong) NSMutableArray *firstDateSource;
@property (nonatomic, strong) NSMutableArray *secDateSource;
@property (nonatomic, strong) UIView *pictureView;
@property (nonatomic, strong) UIView *footView;
@property (nonatomic, weak) MBProgressHUD* HUD;
@end

@implementation YWModifyMeterReadingTableViewController

- (instancetype)init{
    return [super initWithStyle:UITableViewStyleGrouped];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"修改抄表读数";
    self.view.backgroundColor = [UIColor customBackgroudColor];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"提交" style:UIBarButtonItemStylePlain target:self action:@selector(postModifyMeterRead:)];
    
    [self.tableView registerClass:[YWMeterReadingDetailRecordCell class] forCellReuseIdentifier:YWMeterReadingDetailRecordCellIdentifier];
    [self.tableView registerClass:[YWLocationCell class] forCellReuseIdentifier:YWLocationCellIdentifier];
    [self.tableView registerClass:[YWWriteMeterReadingNumberCell class] forCellReuseIdentifier:YWWriteMeterReadingNumberCellIdentifier];
    [self.tableView registerClass:[YWWriteNoteCell class] forCellReuseIdentifier:YWWriteNoteCellIdentifier];
    self.tableView.tableFooterView = self.footView;
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    self.tableView.estimatedRowHeight = 44.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
}

- (NSMutableArray *)firstDateSource{
    if (!_firstDateSource) {
        _firstDateSource = [NSMutableArray array];
        
        [_firstDateSource addObject:[self equipmentName]];
        [_firstDateSource addObject:[self ownCode]];
        [_firstDateSource addObject:[self rate]];
        [_firstDateSource addObject:[self companyName]];
        [_firstDateSource addObject:[self place]];
        [_firstDateSource addObject:[self readingTime]];
    }
    return _firstDateSource;
}

- (NSMutableArray*)secDateSource{
    if (!_secDateSource) {
        _secDateSource = [NSMutableArray array];
        [_secDateSource addObject:[self useNumberText]];
        [_secDateSource addObject:[self monthLabel]];
//        [_secDateSource addObject:[self notoLabel]];
    }
    return _secDateSource;
}

- (NSString *)equipmentName{
    YWEquipment *equipment = [[YWEquipmentManager shareManager]equipmentWithId:self.meterReadingRecord.equipmentId];
    NSString *equipmentName = [NSString stringWithFormat:@"设备名称: %@",equipment.equipmentName?:@""];
    return equipmentName;
}

- (NSString *)ownCode{
    YWEquipment *equipment = [[YWEquipmentManager shareManager]equipmentWithId:self.meterReadingRecord.equipmentId];
    NSString * ownCode = [NSString stringWithFormat:@"表号: %@",equipment.ownCode?:@"无"];
    return ownCode;
}

- (NSString *)rate{
    NSString * rate = [NSString stringWithFormat:@"倍率: %.1f",self.meterReadingRecord.rate>0?self.meterReadingRecord.rate:1.0];
    return rate;
}

- (NSString *)companyName{
    YWMeterProperty *meterProperty = [[YWEquipmentManager shareManager] meterPropertyWithEquipmentId:self.meterReadingRecord.equipmentId];
    NSString * companyName = [NSString stringWithFormat:@"单位名称: %@",meterProperty.companyName.length ? meterProperty.companyName:@"无"];
    return companyName;
}

- (NSString *)place{
    YWMeterProperty *meterProperty = [[YWEquipmentManager shareManager] meterPropertyWithEquipmentId:self.meterReadingRecord.equipmentId];
    NSString * place = [NSString stringWithFormat:@"房号: %@",meterProperty.place.length ? meterProperty.place:@"无"];
    return place;
}

- (NSString *)readingTime{
    NSString *recordTime = [YWCommonTool showFullTime:self.meterReadingRecord.readingTime/1000];
    NSString * readingTime = [NSString stringWithFormat:@"抄表时间: %@",recordTime];
    return readingTime;
}

- (NSString *)useNumberText{
    CGFloat useNumber = self.meterReadingRecord.usedAmount;
    NSInteger wEquipmentTypeId = [[YWMeterReadingManager shareManager]waterMeterEquipmentTypeId];
    NSInteger eEquipmentTypeId = [[YWMeterReadingManager shareManager]electricMeterEquipmentTypeId];
    NSInteger gEquipmentTypeId = [[YWMeterReadingManager shareManager]gasMeterEquipmentTypeId];
    if (self.meterReadingRecord.equipmentTypeId == wEquipmentTypeId) {
        NSString * useNumberText = useNumber>0?[NSString stringWithFormat:@"本次用水量: %.2f立方米",useNumber]:@"本次用水量: -";
        return useNumberText;
    }else if (self.meterReadingRecord.equipmentTypeId == eEquipmentTypeId) {
        NSString * useNumberText = useNumber>0?[NSString stringWithFormat:@"本次用电量: %.2f度",useNumber]:@"本次用电量: -";
        return useNumberText;
    }else if (self.meterReadingRecord.equipmentTypeId == gEquipmentTypeId) {
        NSString * useNumberText = useNumber>0?[NSString stringWithFormat:@"本次用气量: %.2f立方米",useNumber]:@"本次用气量: -";
        return useNumberText;
    }else{
        NSString * useNumberText = useNumber>0?[NSString stringWithFormat:@"本次用量: %.2f",useNumber]:@"本次用量: -";
        return useNumberText;
    }
}

- (NSString *)monthLabel{
    NSString * monthLabel = [NSString stringWithFormat:@"抄表月份: %@",self.meterReadingRecord.readingMonth?:@"未填写"];
    return monthLabel;
}

- (NSString *)notoLabel{
    NSString * notoLabel = [NSString stringWithFormat:@"备注: %@",self.meterReadingRecord.note.length?self.meterReadingRecord.note:@"未填写"];
    return notoLabel;
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 1){
        return [self.firstDateSource count];
    }else if (section == 3){
        return [self.secDateSource count];
    }else{
        return 1;
    }
}

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    if (indexPath.section == 0) {
//       return [tableView fd_heightForCellWithIdentifier:YWLocationCellIdentifier cacheByIndexPath:indexPath configuration:^(YWLocationCell *cell) {
//           [self configureLocationCell:cell atIndexPath:indexPath];
//        }];
//    }else{
//        CGFloat rowH = [tableView fd_heightForCellWithIdentifier:YWMeterReadingDetailRecordCellIdentifier cacheByIndexPath:indexPath configuration:^(YWMeterReadingDetailRecordCell *cell) {
//            cell.contentLabel.text = self.dateSource[indexPath.row];
//        }];
//        return rowH>35?rowH:35;
//    }
//}

- (void)configureLocationCell:(YWLocationCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    cell.fd_enforceFrameLayout = NO;
    YWEquipment *equipment = [[YWEquipmentManager shareManager]equipmentWithId:self.meterReadingRecord.equipmentId];
    cell.locationText = [[YWBuildingManager shareManager] equipmentLocation:equipment];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        YWLocationCell * cell = [tableView dequeueReusableCellWithIdentifier:YWLocationCellIdentifier];
        [self configureLocationCell:cell atIndexPath:indexPath];
        return cell;
    }else if (indexPath.section == 1){
        YWMeterReadingDetailRecordCell * cell = [tableView dequeueReusableCellWithIdentifier:YWMeterReadingDetailRecordCellIdentifier];
        cell.contentLabel.text = self.firstDateSource[indexPath.row];
        return cell;
    }else if (indexPath.section == 2){
        YWWriteMeterReadingNumberCell * cell = [tableView dequeueReusableCellWithIdentifier:YWWriteMeterReadingNumberCellIdentifier];
        cell.placeholderStr = [NSString stringWithFormat:@"%.2f",self.meterReadingRecord.thisReadNumber];
        cell.delegate = self;
        return cell;
    }else if (indexPath.section == 3){
        YWMeterReadingDetailRecordCell * cell = [tableView dequeueReusableCellWithIdentifier:YWMeterReadingDetailRecordCellIdentifier];
        cell.contentLabel.text = self.secDateSource[indexPath.row];
        return cell;
    }else{
        YWWriteNoteCell * cell = [tableView dequeueReusableCellWithIdentifier:YWWriteNoteCellIdentifier];
        cell.delegate = self;
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 4) {
        return 90;
    }else{
        return UITableViewAutomaticDimension;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}

- (void)scrollViewWillBeginDragging:(UIScrollView*)scrollView
{
    [self.view endEditing:YES];
}

- (void)transmitTextFieldValue:(NSString *)readingValue cell:(UITableViewCell *)cell{
    writtingReadingNumber = readingValue;
}

- (void)passNote:(NSString*)note
{
    noteString = note;
}

#pragma mark - tableview section foot view

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (section == 4) {
        return self.pictureView;
    }else{
        return nil;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 4) {
        return self.pictureView.frame.size.height;
    }else{
        return 0.01;
    }
}

- (UIView *)pictureView{
    if (!_pictureView) {
        UIView *view = [[UIView alloc] init];
        view.backgroundColor = [UIColor whiteColor];
        _pictureView = view;
        CGFloat repairImageViewH = 0;
        NSArray *pictureArray = self.meterReadingRecord.pictures;
        if (pictureArray.count==0) {
            pictureArray = [[YWMeterReadingManager shareManager] recordPictureWithRecordId:self.meterReadingRecord.meterRecordId recordType:YWPictureRecordTypeMeterReading];
        }
        if (pictureArray.count>0) {
            YWPhotoView* imageV = [[YWPhotoView alloc] init];
            imageV.canAddPhoto = NO;
            imageV.photosArray = pictureArray;
            [imageV setFrame:CGRectMake(0, 10, imageV.frame.size.width, imageV.frame.size.height)];
            [_pictureView addSubview:imageV];
            repairImageViewH = imageV.frame.size.height+20;
        }
        [_pictureView setFrame:CGRectMake(0, 0, SCREEN_WIDTH, repairImageViewH)];
    }
    return _pictureView;
}

- (UIView *)footView{
    if (!_footView) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 80)];
        _footView = view;
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, SCREEN_WIDTH-15*2, 80)];
        label.backgroundColor = [UIColor customBackgroudColor];
        label.textColor = [UIColor customTextGrayBlackColor];
        label.numberOfLines = 0;
        label.font = kContentFont;
        label.text = @"请注意! 本次读数和上次读数为仪表终端读数,最终使用量需乘以倍率,实际水/电/煤气使用量为(本次读数-上次读数)*倍率";
        [_footView addSubview:label];
    }
    return _footView;
}

- (void)postModifyMeterRead:(id)sender{
    [self.view endEditing:YES];
    if ([writtingReadingNumber floatValue] < self.meterReadingRecord.thisReadNumber) {
        [YWCommonTool showTextHUDWithContent:@"读数不能小于上次记录读数"];
        return;
    }
    if (noteString.length==0){
        [YWCommonTool showTextHUDWithContent:@"请填写备注信息"];
        return;
    }
    NSDate* nowDate = [NSDate date];
    NSTimeInterval nowTime =[nowDate timeIntervalSince1970];
    self.meterReadingRecord.readingTime = nowTime*1000;
    self.meterReadingRecord.note = noteString;
    self.meterReadingRecord.thisReadNumber = [writtingReadingNumber floatValue];
    self.meterReadingRecord.usedAmount = self.meterReadingRecord.thisReadNumber-self.meterReadingRecord.usedAmount;
    //提交
    [[YWMeterReadingManager shareManager] modifyThisReadNumberOfMeterReadingRecord:self.meterReadingRecord withBlock:^(BOOL success) {
            if (success) {
                [YWCommonTool showTextHUDWithContent:@"修改成功"];
                self.firstDateSource = nil;
                self.secDateSource = nil;
                [self.tableView reloadData];
                NSDictionary *dic = [NSDictionary dictionaryWithObject:self.meterReadingRecord forKey:@"meterReadingRecord"];
                [[NSNotificationCenter defaultCenter] postNotificationName:KModifyMeterReadSuccessNotification object:nil userInfo:dic];
                [self.navigationController popViewControllerAnimated:YES];
            }else{
                [YWCommonTool showTextHUDWithContent:@"修改失败,请稍后重试"];
            }
            [self.HUD hide:YES afterDelay:0.5];
        }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
